package online.flytool.base.db;

import online.flytool.base.db.handler.FnRsHandler;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 一切的连接关闭都在外部进行
 * @author ：lingchong
 * @date ：Created in 2022/7/3 16:40
 * @description：jdbc的连接类
 * @modified By：
 * @version: $
 */
public class SqlExecutor {

    /**
     * 根据sql进行修改
     * @param sql
     * @param params
     */
    public static int update(Connection conn, String sql, Object... params)  {
        int row=0;
        try(PreparedStatement ps = conn.prepareStatement(sql)) {
            int i=1;
            for (Object param : params) {
                ps.setObject(i,param);
            }
            row=ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return row;
    };

    /**
     * 返回list集合
     * @param conn
     * @param sql
     * @param params
     * @return
     * @param <T>
     */
    public static <T> List<T> selectList(Connection conn, String sql,Class<T> targetCla, FnRsHandler<T> fnRsHandler , Object... params)  {
        List list=new ArrayList();
        try(PreparedStatement ps = conn.prepareStatement(sql);) {
            int i=1;
            for (Object param : params) {
                ps.setObject(i,param);
            }
            try(ResultSet rs = ps.executeQuery()) {
                while(rs.next()){
                    list.add(fnRsHandler.handle(rs,targetCla));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //  为空就返回空集合,可以加速gc并且避免对于整个空对象进行操作
        if(list.isEmpty()){
            return Collections.EMPTY_LIST;
        }
        return list;
    };



    public void close(AutoCloseable... autoCloseables)throws RuntimeException{
        RuntimeException exec=null;
        for (AutoCloseable autoCloseable : autoCloseables) {
            if(autoCloseable==null){
                continue;
            }
            try {
                autoCloseable.close();
            } catch (Exception e) {
                exec=new RuntimeException(e);
            }
        }
        if(exec!=null){
            throw exec;
        }
    }

}